

from django import forms
from web.forms.boot_strap import BootStrap
from web import models
from django.core.exceptions import ValidationError
from utils.tencent.cos import check_file
from qcloud_cos.cos_exception import CosServiceError

class FileFolderModelForm(BootStrap, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self,request, parent_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_object = parent_object

    def clean_name(self):
        name = self.cleaned_data.get("name")
        # 去数据库判断，当前目录下下的文件夹是否存在
        query_set = models.FileRepository.objects.filter(file_type=2, name=name,
                                             project=self.request.tracer.project)
        if self.parent_object:
            exists = query_set.filter(parent=self.parent_object).exists()
        else:
            exists = query_set.filter(parent__isnull=True).exists()

        if exists:
            raise ValidationError("文件夹已存在")

        return name


class FileModelForm(forms.ModelForm):
    # etag = forms.CharField(label="etag")
    # print("************")
    class Meta:
        model = models.FileRepository
        exclude = ["project", "file_type", "update_user", "update_datetime"]

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        return "https://{}".format(self.cleaned_data.get("file_path"))





'''
    def clean(self):
        key = self.cleaned_data.get("key")
        etag = self.cleaned_data.get("etag")
        size = self.cleaned_data.get("size")

        if not key or not etag:
            return self.cleaned_data

        # 向cos校验文件是否合法
        # SDK的功能
        try:
            result = check_file(self.request.tracer.project.bucket, self.request.tracer.project.region,key)
            # print(result)
            # {'Content-Type': 'text/plain', 'Content-Length': '1971', 'Connection': 'keep-alive', 'Date': 'Tue, 02 Feb 2021 08:00:15 GMT', 'ETag': '"75bfffcc55ad9052d9ba2090debbdb2a"', 'Last-Modified': 'Tue, 02 Feb 2021 08:00:15 GMT', 'Server': 'tencent-cos', 'x-cos-hash-crc64ecma': '18439384028921592943', 'x-cos-request-id': 'NjAxOTA2OGZfMjBiNDU4NjRfNTQ2NF82MmRkZjhl'}
        except CosServiceError as e:
            self.add_error("key", "文件不存在")
            return self.cleaned_data
        if etag != result.get("ETag"):
            self.add_error("etag", "ETag错误")

        if size != int(result.get("Content-Length")):
            self.add_error("size", "文件大小错误")

        return self.cleaned_data
'''


